%%%-------------------------------------------------------------------
%%% File    : p39.erl
%%% Author  : Plamen Dragozov <plamen at dragozov.com>
%%% Description : 
%%% If p is the perimeter of a right angle triangle with integral 
%%% length sides, {a,b,c}, there are exactly three solutions for 
%%% p = 120.
%%%
%%% {20,48,52}, {24,45,51}, {30,40,50}
%%%
%%% For which value of p = 1000, is the number of solutions maximised?
%%%
%%%
%%% Created : 29 Dec 2008
%%%-------------------------------------------------------------------
-module(p39).

%% API
-compile(export_all).

%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: solution(PMax) -> P
%% Description: Calculate the P bellow PMax for which the number of solutions is maximized.
%%--------------------------------------------------------------------
solution(PMax)->
    lists:foldl(fun(X, {_, MaxS} = Acc) -> 
                        S = solutions_count(X),
                        case S > MaxS of
                            true -> {X, S};
                            _ -> Acc
                        end
                end, 
                {0, 0}, 
                lists:seq(3,PMax)).

%%====================================================================
%% Internal functions
%%====================================================================

% A<=B<C
% P = A+B+C => A <= P/3, B <= P/2 
% C**2 = A**2 + B**2 
solutions_count(P) ->
    %list comprehensions to the rescue, just encoding the problem in the guards
    length([{A,B} || A<-lists:seq(1, P div 3), B <- lists:seq(A, P div 2), (P-A-B)*(P-A-B)=:= A*A + B*B]).
